package com.baizhi.service.impl;

import com.baizhi.dao.UserDao;
import com.baizhi.entity.User;
import com.baizhi.service.UserService;
import com.baizhi.util.MyBatisUtils;
import org.apache.ibatis.session.SqlSession;

public class UserServiceImpl implements UserService {
    @Override
    public boolean login(String username, String password) {
        boolean result = false;
        SqlSession sqlSession = MyBatisUtils.openSession();
        UserDao dao = sqlSession.getMapper(UserDao.class);
        User user = dao.selectByUsername(username);
        if(user!=null&&user.getPassword().equals(password)){
            result = true;
        }
        MyBatisUtils.close(sqlSession);
        return result;
    }

    @Override
    public void register(User u) {
        SqlSession sqlSession = MyBatisUtils.openSession();
        try {
            UserDao dao = sqlSession.getMapper(UserDao.class);
            dao.insertUser(u);
            sqlSession.commit();
        } catch (Exception e) {
            sqlSession.rollback();
        } finally {
            MyBatisUtils.close(sqlSession);
        }
    }

    @Override
    public User selectByUsername(String username) {
        SqlSession sqlSession = MyBatisUtils.openSession();
        UserDao dao = sqlSession.getMapper(UserDao.class);
        User user = dao.selectByUsername(username);
        return user;
    }
}
